package cc.siyecao.fastdfs.command.storage;

import cc.siyecao.fastdfs.extception.FastDfsException;
import cc.siyecao.fastdfs.model.RecvPackageInfo;
import cc.siyecao.fastdfs.model.StoreFile;
import cc.siyecao.fastdfs.protocol.ProtocolConstants;
import cc.siyecao.fastdfs.util.ProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import static cc.siyecao.fastdfs.protocol.ProtocolConstants.ERR_NO_EINVAL;

/**
 * 文件修改命令
 *
 * @author lyt
 */
public class FileNameCommand extends FdfsStorageCommand<StoreFile> {

    /**
     * 文件名修改命令
     *
     * @param groupName
     * @param appenderFileName
     */
    public FileNameCommand(String groupName, String appenderFileName) {
        this.groupName = groupName;
        this.fileName = appenderFileName;
    }

    @Override
    protected void send(OutputStream out, Charset charset) throws Exception {
        byte[] header;
        byte[] appenderFilenameBytes;
        int offset;
        long body_len;

        if ((groupName == null || groupName.length() == 0) || (fileName == null || fileName.length() == 0)) {
            this.errno = ERR_NO_EINVAL;
            throw new FastDfsException( "groupName and fileName can not be null" );
        }
        appenderFilenameBytes = fileName.getBytes( charset );
        body_len = appenderFilenameBytes.length;

        header = ProtocolUtil.packHeader( STORAGE_PROTO_CMD_REGENERATE_APPENDER_FILENAME, body_len, (byte) 0 );
        byte[] wholePkg = new byte[(int) (header.length + body_len)];
        System.arraycopy( header, 0, wholePkg, 0, header.length );
        offset = header.length;

        System.arraycopy( appenderFilenameBytes, 0, wholePkg, offset, appenderFilenameBytes.length );
        offset += appenderFilenameBytes.length;
        out.write( wholePkg );
    }

    @Override
    protected StoreFile receive(InputStream in, Charset charset) throws Exception {
        RecvPackageInfo pkgInfo = ProtocolUtil.recvPackage( in, STORAGE_PROTO_CMD_RESP, -1 );
        this.errno = pkgInfo.errno;
        if (pkgInfo.errno != 0) {
            return null;
        }

        if (pkgInfo.body.length <= ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN) {
            throw new FastDfsException( "body length: " + pkgInfo.body.length + " <= " + ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN );
        }
        String newGroupName = new String( pkgInfo.body, 0, ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN ).trim();
        String remoteFileName = new String( pkgInfo.body, ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN, pkgInfo.body.length - ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN );
        return new StoreFile( newGroupName, remoteFileName );
    }
}
